<template>
  <div class="data-sync-manager">
    <el-card class="sync-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <i class="el-icon-refresh"></i>
            <span>当前持仓股票同步</span>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="startSync" 
              :loading="syncing"
              :disabled="syncing"
            >
              {{ syncing ? '同步中...' : '开始同步' }}
            </el-button>
          </div>
        </div>
      </template>

      <div class="sync-content">
        <!-- 同步状态显示 -->
        <div class="sync-status" v-if="syncStarted">
          <el-steps :active="currentStep" finish-status="success" align-center>
            <el-step 
              title="获取股票列表" 
              :description="stepDescriptions[0]"
              :status="getStepStatus(0)"
            />
            <el-step 
              title="处理股票数据" 
              :description="stepDescriptions[1]"
              :status="getStepStatus(1)"
            />
            <el-step 
              title="同步完成" 
              :description="stepDescriptions[2]"
              :status="getStepStatus(2)"
            />
          </el-steps>
        </div>

        <!-- 当前持仓股票列表 -->
        <div class="current-stocks" v-if="currentStocks.length > 0">
          <h4 class="section-title">
            <i class="el-icon-s-data"></i>
            当前持仓股票 ({{ currentStocks.length }} 只)
          </h4>
          
          <div class="stocks-grid">
            <div 
              v-for="stock in currentStocks" 
              :key="stock.stockCode"
              class="stock-item"
              :class="{ 'processing': processedStocks.has(stock.stockCode) }"
            >
              <div class="stock-info">
                <div class="stock-name">{{ stock.stockName }}</div>
                <div class="stock-code">{{ stock.stockCode }}</div>
              </div>
              
              <div class="stock-details">
                <div class="detail-item">
                  <span class="label">池中股数:</span>
                  <span class="value">{{ stock.poolShares }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">待买股数:</span>
                  <span class="value">{{ stock.pendingShares }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">剩余股数:</span>
                  <span class="value remaining-shares">{{ stock.remainingShares }}</span>
                </div>
              </div>

              <div class="stock-status">
                <el-tag 
                  v-if="processedStocks.has(stock.stockCode)"
                  type="success" 
                  size="mini"
                  effect="dark"
                >
                  已处理
                </el-tag>
                <el-tag 
                  v-else-if="syncing"
                  type="info" 
                  size="mini"
                  effect="plain"
                >
                  等待处理
                </el-tag>
                <el-tag 
                  v-else
                  type="info" 
                  size="mini"
                  effect="plain"
                >
                  待同步
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 同步日志 -->
        <div class="sync-logs" v-if="syncLogs.length > 0">
          <h4 class="section-title">
            <i class="el-icon-document"></i>
            同步日志
          </h4>
          
          <div class="logs-container">
            <div 
              v-for="(log, index) in syncLogs" 
              :key="index"
              class="log-item"
              :class="log.type"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!syncStarted && currentStocks.length === 0 && !loading" class="empty-state">
          <el-empty 
            description="点击开始同步获取当前持仓股票数据" 
            :image-size="100"
          />
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="3" animated />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getCurrentStocks, syncStockStatus } from '@/api/stockTrading'

export default {
  name: 'DataSyncManager',
  data() {
    return {
      currentStocks: [],
      loading: false,
      syncing: false,
      syncStarted: false,
      currentStep: 0,
      processedStocks: new Set(),
      syncLogs: [],
      stepDescriptions: [
        '正在获取股票池和待买入池数据...',
        '正在处理股票数据...',
        '数据同步完成'
      ]
    }
  },
  methods: {
    async startSync() {
      this.syncing = true
      this.syncStarted = true
      this.currentStep = 0
      this.processedStocks.clear()
      this.syncLogs = []
      
      this.addLog('info', '开始数据同步...')
      
      try {
        // 第一步：获取当前存在的股票
        await this.fetchCurrentStocks()
        
        // 第二步：处理股票数据
        await this.processStockData()
        
        // 第三步：完成同步
        this.completeSync()
        
      } catch (error) {
        this.addLog('error', `同步失败: ${error.message}`)
        this.$message.error('数据同步失败')
      } finally {
        this.syncing = false
      }
    },
    
    async fetchCurrentStocks() {
      this.loading = true
      this.currentStep = 0
      this.stepDescriptions[0] = '正在获取股票池和待买入池数据...'
      
      try {
        this.addLog('info', '正在调用获取当前存在股票接口...')
        
        const response = await getCurrentStocks()
        
        if (response.code === 200) {
          this.currentStocks = response.data || []
          this.addLog('success', `成功获取 ${this.currentStocks.length} 只当前持仓股票`)
          this.stepDescriptions[0] = `已获取 ${this.currentStocks.length} 只股票`
          this.currentStep = 1
          
          // 输出股票详情到日志
          this.currentStocks.forEach(stock => {
            this.addLog('info', 
              `${stock.stockName}(${stock.stockCode}): 池中${stock.poolShares}股, 待买${stock.pendingShares}股, 剩余${stock.remainingShares}股`
            )
          })
          
        } else {
          throw new Error(response.msg || '获取股票数据失败')
        }
        
      } catch (error) {
        this.addLog('error', `获取股票数据失败: ${error.message}`)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async processStockData() {
      this.stepDescriptions[1] = '正在处理股票数据...'
      
      if (this.currentStocks.length === 0) {
        this.addLog('warning', '没有需要处理的股票数据')
        this.stepDescriptions[1] = '无股票需要处理'
        this.currentStep = 2
        return
      }
      
      this.addLog('info', `开始处理 ${this.currentStocks.length} 只股票的数据...`)
      
      // 模拟处理每只股票的数据
      for (let i = 0; i < this.currentStocks.length; i++) {
        const stock = this.currentStocks[i]
        
        try {
          // 这里可以添加具体的处理逻辑
          // 比如同步T+0交易数据、更新市值等
          await this.processIndividualStock(stock)
          
          this.processedStocks.add(stock.stockCode)
          this.addLog('success', `${stock.stockName}(${stock.stockCode}) 处理完成`)
          
          // 更新进度
          const progress = Math.round(((i + 1) / this.currentStocks.length) * 100)
          this.stepDescriptions[1] = `已处理 ${i + 1}/${this.currentStocks.length} 只股票 (${progress}%)`
          
          // 添加延迟避免请求过快
          if (i < this.currentStocks.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 500))
          }
          
        } catch (error) {
          this.addLog('error', `处理 ${stock.stockName}(${stock.stockCode}) 失败: ${error.message}`)
        }
      }
      
      this.currentStep = 2
    },
    
    async processIndividualStock(stock) {
      // 这里是处理单个股票的逻辑
      // 1. 根据股票编码查询最新信息
      // 2. 检查今天的数据是否存在，如果不存在则生成
      
      this.addLog('info', `正在处理 ${stock.stockName}(${stock.stockCode})...`);
      
      try {
        // 调用后端的同步接口
        const response = await syncStockStatus(stock.stockCode);
        
        if (response.code === 200) {
          const data = response.data;
          if (data.action === 'already_exists') {
            this.addLog('success', `${stock.stockName}(${stock.stockCode}) - 今日数据已存在`);
          } else if (data.action === 'created_today') {
            this.addLog('success', `${stock.stockName}(${stock.stockCode}) - 成功生成今日数据（基于 ${data.basedOnDate}），已动态获取做T收益`);
          }
        } else {
          this.addLog('error', `${stock.stockName}(${stock.stockCode}) - ${response.msg}`);
          throw new Error(response.msg);
        }
      } catch (error) {
        this.addLog('error', `处理 ${stock.stockName}(${stock.stockCode}) 失败: ${error.message}`);
        throw error;
      }
    },
    
    completeSync() {
      this.stepDescriptions[2] = `同步完成，共处理 ${this.processedStocks.size} 只股票`
      this.addLog('success', '数据同步完成！')
      this.$message.success('数据同步完成')
      
      // 发出同步完成事件
      this.$emit('sync-complete', {
        totalStocks: this.currentStocks.length,
        processedStocks: this.processedStocks.size,
        stocks: this.currentStocks
      })
    },
    
    addLog(type, message) {
      const log = {
        type,
        message,
        time: new Date().toLocaleTimeString()
      }
      this.syncLogs.push(log)
      
      // 限制日志数量
      if (this.syncLogs.length > 50) {
        this.syncLogs.splice(0, 10)
      }
    },
    
    getStepStatus(stepIndex) {
      if (stepIndex < this.currentStep) {
        return 'finish'
      } else if (stepIndex === this.currentStep && this.syncing) {
        return 'process'
      } else if (stepIndex === this.currentStep && !this.syncing && this.syncStarted) {
        return 'finish'
      }
      return 'wait'
    }
  }
}
</script>

<style scoped>
.data-sync-manager {
  padding: 10px;
  max-width: 1825px;
  margin: 0 auto;
}

.sync-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  color: #409EFF;
}

.sync-info {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.sync-status {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.section-title i {
  color: #E6A23C;
}

.stocks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.stock-item {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  transition: all 0.3s ease;
}

.stock-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stock-item.processing {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.stock-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stock-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stock-code {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.stock-details {
  margin-bottom: 10px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 14px;
}

.label {
  color: #606266;
}

.value {
  font-weight: 600;
  color: #303133;
}

.remaining-shares {
  color: #409EFF;
  font-weight: bold;
}

.stock-status {
  text-align: right;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 10px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 0;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #909399;
  font-size: 12px;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-item.success .log-message {
  color: #67c23a;
}

.log-item.error .log-message {
  color: #f56c6c;
}

.log-item.warning .log-message {
  color: #e6a23c;
}

.log-item.info .log-message {
  color: #303133;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.loading-state {
  padding: 30px 0;
}

@media (max-width: 768px) {
  .stocks-grid {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .stock-item {
    padding: 12px;
  }
}
</style>